/* 
 * C语言利用共享内存和管道实现客户端聊天
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <cassert>
#include <cstdlib>
#include <cerrno>
#include <signal.h>
#include <sys/epoll.h>
#include <sys/mman.h>
#include <sys/wait.h>
using namespace std;

const int USER_LIMIT = 5;   // 用户限制
const int BUFFER_SIZE = 1024; // 缓冲区大小
const int FD_LIMIT = 65535; // 文件描述符限制
const int MAX_EVENT_NUMBER = 1024;  // epoll数量限制
const int PROCESS_LIMIT 65535; // 进程限制

struct clientData {
    sockaddr_in address;    // 客户端地址
    int connFd;             // socket文件描述符
    pid_t pid;              // 子进程pid
    int pipeFd[2];          // 和父进程通信的管道
};

static const char* shmName = "/myShm";
int sigPipeFd[2];
int epollFd;
int listenFd;
int shmFd;
char* shareMem = 0;
clientData* users = 0;
int* subProcess = 0;
int userCount = 0;
bool stopChild = false;

int setNonBlocking(int fd) {
    int oldOption = fcntl(fd, F_GETFL);
    int newOption = oldOption | O_NONBLOCK;
    fcntl(fd, F_SETFL, newOption);
    return oldOption;
}

void addFd(int epollFd, int fd) {
    epoll_event event;
    event.data.fd = fd;
    event.events = EPOLLIN | EPOLLET;
    epoll_ctl (epollFd, EPOLL_CTL_ADD, fd, &event);
    setNonBlocking(fd);
}

void sigHandler(int sig) {
    int saveErrno = errno;
    int msg = sig;
    send(sigPipeFd[1], (char*)&mag, 1, 0);
    errno = saveErrno;
}

void delResource() {
    close(sigPipeFd[0]);
    close(sigPipeFd[1]);
    close(listenFd);
    close(epollFd);
    shm_unlink(shmName);
    delete[] users;
    delete[] subProcess;
}

void childTermHandler(int sig) {
    stopChild = true;
}

int runChild(int idx, clientData* users, char* shareMem) {
    epoll_event events[MAX_EVENT_NUMBER];
    int childEpollFd = epoll_create(5);
    assert(childEpollFd != -1);
    int connFd = users[idx].connFd;
    int pipeFd = users[idx].pipeFd[1];
    addFd(childEpollFd, pipeFd);
    int ret;
    addsig(SIGTERM, childTermHandler, false);

    while(!stopChild) {
        int number = epoll_wait(childEpollFd, events, MAX_EVENT_NUMBER, -1);
        if(number < 0 && errno != EINTR) {
            cout << "epoll failure" << endl;
            break;
        }

        for(int i = 0; i < number; ++i) {
            int sockFd = events[i].data.fd;

            if(sockFd == connFd && events[i].events & EPOLLIN) {
                memset(shareMem + idx * BUFFER_SIZE, 0, BUFFER_SIZE);
                ret = recv(connFd, shareMem + idx * BUFFER_SIZE, BUFFER_SIZE - 1, 0);
                if (ret < 0) {
                    if (errno != EAGAIN) {
                        stopChild = true;
                    }
                }
                else if (ret == 0) {
                    stopChild = true; // 对方关闭连接
                }
                else {
                    send(pipeFd, (char*)&idx, sizeof(idx), 0); // 通过管道通知主进程，并且告知共享内存中idx有数据
                }
            }
            else if (sockFd == pipeFd && events[i].events & EPOLLIN) {
                int client = 0;
                ret = recv(sockFd, (char*)&client, sizof(client), 0); //接收其它clint发来的消息
                if (ret < 0) {
                    if(errno != EAGAIN) {
                        stopChild = true;
                    }
                }
                else if(ret == 0) {
                    stopChild = true;
                }
                else {
                    send (connFd, shareMem + client * BUFFER_SIZE, BUFFER_SIZE, 0);
                }
            }
            else {
                continue;
            }
        }
    }
    close(connFd);
    close(pipeFd);
    close(childEpollFd);
    return 0;
}

int main(int argc, char* argv[])
{
    if (argc <= 2) {
        cerr << "Usage: " << argv[0] << " <IP> <Port>" << endl;
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi(argv[2]);

    int ret = 0;
    struct sockaddr_in serverAddress;
    memset(&serverAddress, 0, sizeof(serverAddress));
    serverAddress.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &serverAddress.sin_addr);
    serverAddress.sin_port = htons(port);

    listenFd = socket(AF_INET, SOCK_STREAM, 0);
    assert(listenFd >= 0);

    ret = bind(listenFd, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
    assert(ret != -1);

    ret = listen(listenFd, USER_LIMIT);
    assert(ret != -1);

    userCount = 0;
    users = new clientData[USER_LIMIT + 1];
    subProcess = new int[PROCESS_LIMIT];
    for(int i = 0; i < PROCESS_LIMIT; ++i) {
        subProcess[i] = -1;
    }

    epoll_event events[MAX_EVENT_NUMBER]; // 事件集合
    epollFd = epoll_create(5);
    assert(epollFd != -1);
    addFd(epollFd, listenFd);

    ret = socketpair(AF_INET, SOCK_STREAM, 0, sigPipeFd);
    assert(ret != -1);
    setNonBlocking(sigPipeFd[1]);
    addFd(epollFd, sigPipeFd[0]);

    addsig(SIGCHLD, sigHandler);
    addsig(SIGTERM, sigHandler);
    addsig(SIGINT, sigHandler);
    addsig(SIGPIPE, SIG_IGN);
    bool stopServer = false;
    bool terminate = false;

    shmFd = shm_open(shmName, O_CREAT | O_RDWR, 0666);
    assert(shmFd != -1);
    ret = ftruncate(shmFd, USER_LIMIT * BUFFER_SIZE);
    assert(ret != -1);

    shareMem = (char*)mmap(nullptr, USER_LIMIT * BUFFER_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
    assert(shareMem != MAP_FAILED);
    close(shmfd);

    while(!stopServer)
    {
        int number = epoll_wait(fds, events, MAX_EVENT_NUMBER, -1);    // 阻塞等待事件
        if (number < 0 && errno != EINTR) {
            cerr << "epoll failure " << endl;
            break;
        }

        for (int i = 0; i < number; ++i) {
            int sockFd = events[i].data.fd;
            if(sockFd == listenFd) {
                struct sockaddr_in clientAddress;
                socklen_t clientAddrLen = sizeof(clientAddress);
                int connFd = accept(listenFd, (struct sockaddr*)&clientAddress, &clientAddrLen);
                if (connFd < 0) {
                    cout << "errno is: " << errno << endl;
                    continue;
                }
                if(userCount >= USER_LIMIT) {
                    const char* info = "too many users\n";
                    cout << info;
                    send(connFd, info, strlen(info), 0);
                    close(connFd);
                    continue; 
                }
                users[userCount].address = clientAddress;
                users[userCount].connFd = connFd;

                ret = socketpair(AF_INET, SOCK_STREAM, 0, users[userCount].pipeFd);
                assert(ret != -1);
                pid_t pid = fork();
                if(pid < 0) {
                    close(connFd);
                    continue;
                }
                else if(pid == 0) {
                    // 子进程关闭父进程的文件描述符
                    close(epollFd);
                    close(listenFd);
                    close(users[userCount].pipeFd[0]); 
                    close(sigPipeFd[0]);
                    close(sigPipeFd[1]);
                    runChild(userCount, users, shareMem);
                    munmap((void*)shareMem, USER_LIMIT * BUFFER_SIZE);
                    exit(0);
                }
                else {
                    close(connFd);
                    close(uses[userCount].pipeFd[1]);
                    addFd(epollFd, users[userCount].pipeFd[0]);
                    users[userCount].pid = pid;

                    subProcess[pid] = userCount;
                    userCount++;
                }
            }
            else if(sockFd == sigPipeFd[0] && events[i].events & EPOLLIN) {
                int sig;
                char signals[1024];
                ret = recv(sigPipeFd[0], signals, sizeof(signals), 0);
                if (ret == -1) {
                    continue;
                }
                else if (ret == 0) {
                    continue;
                }
                else {
                    for (int i = 0; 9 < ret; ++i) {
                        switch(signals[i]) {
                            case SIGCHLD: {
                                pid_t pid;
                                int stat;
                                while ((pid = waitpid(-1, &stat, WNOHANG)) > 0) {
                                    int delUser = subProcess[pid];
                                    subProcess[pid] = -1;
                                    if(delUser < 0 || delUser > USER_LIMIT) {
                                        continue;
                                    }
                                    epoll_ctl(epollFd, EPOLL_CTL_DEL, users[delUser].pipeFd[0], 0);
                                    close(users[delUser].pipeFd[0]);
                                    users[delUser] = users[--userCount];
                                    subProcess[users[delUser].pid] = delUser;
                                }
                                if(terminate && userCount == 0) {
                                    stopServer = true;
                                }
                                break;
                            }
                            case SIGTERM: 
                            case SIGINT: {
                                cout << "kill all the child now" << endl;
                                if (userCount == 0) {
                                    stopServer = true;
                                    break;
                                }
                                for (int i = 0; i < userCount; ++i) {
                                    int pid = uses[i].pid;
                                    kill(pid, SIGTERM);
                                }
                                terminate = true;
                                break;
                            }
                            default: {
                                break;
                            }
                        }
                    }
                }
            }
            else if (events[i].events & EPOLLIN) {
                int child = 0;
                ret = recv(sockFd, (char*)&child, sizeof(child), 0);
                cout << "read data from child accross pipe" << endl;
                if (ret == -1) {
                    continue;
                }
                else if (ret == 0) {
                    continue;
                }
                else {
                    for(int j = 0; j < userCount; ++j) {
                        if(users[j].pipeFd[0] != sockFd){
                            cout << "send data to child accross pipe" << endl;
                            send(uses[j].pipeFd[0], (char*)&child, sizeof(child), 0);
                        }
                    }
                }
            }
            
        }
    }

    delResource();
    return 0;
}
*/

#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <cassert>
#include <cstdlib>
#include <cerrno>
#include <signal.h>
#include <sys/epoll.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <memory>
#include <vector>
#include <string>
#include <atomic>
#include <functional>
#include <unordered_map>

using namespace std;

// 服务器配置常量
constexpr int USER_LIMIT = 5;           // 最大用户数量
constexpr int BUFFER_SIZE = 1024;       // 缓冲区大小
constexpr int FD_LIMIT = 65535;         // 文件描述符限制
constexpr int MAX_EVENT_NUMBER = 1024;  // epoll事件最大数量
constexpr int PROCESS_LIMIT = 65535;    // 进程限制

// 客户端数据结构
struct ClientData {
    sockaddr_in address;    // 客户端地址
    int connFd;             // 连接套接字
    pid_t pid;              // 处理该客户端的子进程ID
    int pipeFd[2];          // 与父进程通信的管道
};

// 服务器类 - 封装服务器功能
class ProcessPoolServer {
private:
    const string shmName = "/myShm";     // 共享内存名称
    int sigPipeFd[2];                     // 信号管道
    int epollFd;                          // epoll实例文件描述符
    int listenFd;                         // 监听套接字
    int shmFd;                            // 共享内存文件描述符
    char* shareMem = nullptr;             // 共享内存指针
    vector<ClientData> users;             // 客户端数据数组
    vector<int> subProcess;               // 子进程ID到用户索引的映射
    int userCount = 0;                    // 当前用户数量
    atomic<bool> stopServer{false};       // 服务器停止标志
    atomic<bool> terminate{false};        // 终止标志

public:
    ProcessPoolServer() : users(USER_LIMIT + 1), subProcess(PROCESS_LIMIT, -1) {}
    ~ProcessPoolServer() { delResource(); }

    // 设置非阻塞模式
    static int setNonBlocking(int fd) {
        int oldOption = fcntl(fd, F_GETFL);
        int newOption = oldOption | O_NONBLOCK;
        fcntl(fd, F_SETFL, newOption);
        return oldOption;
    }

    // 添加文件描述符到epoll
    static void addFd(int epollFd, int fd) {
        epoll_event event;
        event.data.fd = fd;
        event.events = EPOLLIN | EPOLLET;
        epoll_ctl(epollFd, EPOLL_CTL_ADD, fd, &event);
        setNonBlocking(fd);
    }

    // 信号处理函数包装器
    static void setupSignalHandler(int sig, function<void(int)> handler) {
        struct sigaction sa;
        memset(&sa, 0, sizeof(sa));
        sa.sa_handler = [](int sig) {
            static auto& signalHandlers = *new unordered_map<int, function<void(int)>>();
            if (signalHandlers.find(sig) != signalHandlers.end()) {
                signalHandlers[sig](sig);
            }
        };
        sigemptyset(&sa.sa_mask);
        sa.sa_flags |= SA_RESTART;
        
        // 存储信号处理函数
        static auto& signalHandlers = *new unordered_map<int, function<void(int)>>();
        signalHandlers[sig] = handler;
        
        sigaction(sig, &sa, nullptr);
    }

    // 信号处理函数 - 父进程
    void sigHandler(int sig) {
        int saveErrno = errno;
        int msg = sig;
        send(sigPipeFd[1], reinterpret_cast<char*>(&msg), 1, 0);
        errno = saveErrno;
    }

    // 子进程信号处理函数
    static void childTermHandler(int sig, atomic<bool>& stopChild) {
        stopChild = true;
    }

    // 释放资源
    void delResource() {
        if (shareMem) {
            munmap(shareMem, USER_LIMIT * BUFFER_SIZE);
            shareMem = nullptr;
        }
        if (shmFd > 0) {
            close(shmFd);
            shmFd = -1;
        }
        if (shmName.size() > 0) {
            shm_unlink(shmName.c_str());
        }
        if (epollFd > 0) {
            close(epollFd);
            epollFd = -1;
        }
        if (listenFd > 0) {
            close(listenFd);
            listenFd = -1;
        }
        if (sigPipeFd[0] > 0) {
            close(sigPipeFd[0]);
            close(sigPipeFd[1]);
            sigPipeFd[0] = sigPipeFd[1] = -1;
        }
    }

    // 子进程运行函数
    static int runChild(int idx, vector<ClientData>& users, char* shareMem) {
        atomic<bool> stopChild{false};
        epoll_event events[MAX_EVENT_NUMBER];
        int childEpollFd = epoll_create(5);
        assert(childEpollFd != -1);
        
        int connFd = users[idx].connFd;
        int pipeFd = users[idx].pipeFd[1];
        
        addFd(childEpollFd, connFd);
        addFd(childEpollFd, pipeFd);
        
        // 设置子进程信号处理
        setupSignalHandler(SIGTERM, [&](int sig) {
            childTermHandler(sig, stopChild);
        });

        while (!stopChild) {
            int number = epoll_wait(childEpollFd, events, MAX_EVENT_NUMBER, -1);
            if (number < 0 && errno != EINTR) {
                cerr << "epoll failure in child process" << endl;
                break;
            }

            for (int i = 0; i < number; ++i) {
                int sockFd = events[i].data.fd;

                // 客户端数据到达
                if (sockFd == connFd && (events[i].events & EPOLLIN)) {
                    memset(shareMem + idx * BUFFER_SIZE, 0, BUFFER_SIZE);
                    int ret = recv(connFd, shareMem + idx * BUFFER_SIZE, BUFFER_SIZE - 1, 0);
                    if (ret < 0) {
                        if (errno != EAGAIN) {
                            cerr << "recv error in child: " << strerror(errno) << endl;
                            stopChild = true;
                        }
                    }
                    else if (ret == 0) {
                        cout << "Client closed connection" << endl;
                        stopChild = true;
                    }
                    else {
                        // 通过管道通知父进程有新数据
                        send(pipeFd, reinterpret_cast<char*>(&idx), sizeof(idx), 0);
                    }
                }
                // 父进程通知有其他客户端消息
                else if (sockFd == pipeFd && (events[i].events & EPOLLIN)) {
                    int client = 0;
                    int ret = recv(sockFd, reinterpret_cast<char*>(&client), sizeof(client), 0);
                    if (ret < 0) {
                        if (errno != EAGAIN) {
                            cerr << "pipe recv error in child: " << strerror(errno) << endl;
                            stopChild = true;
                        }
                    }
                    else if (ret == 0) {
                        stopChild = true;
                    }
                    else {
                        // 发送其他客户端的消息给当前客户端
                        send(connFd, shareMem + client * BUFFER_SIZE, BUFFER_SIZE, 0);
                    }
                }
            }
        }
        
        // 清理资源
        close(connFd);
        close(pipeFd);
        close(childEpollFd);
        return 0;
    }

    // 初始化服务器
    bool init(const char* ip, int port) {
        // 创建监听套接字
        listenFd = socket(AF_INET, SOCK_STREAM, 0);
        if (listenFd < 0) {
            cerr << "socket creation failed" << endl;
            return false;
        }

        // 设置服务器地址
        sockaddr_in serverAddress;
        memset(&serverAddress, 0, sizeof(serverAddress));
        serverAddress.sin_family = AF_INET;
        inet_pton(AF_INET, ip, &serverAddress.sin_addr);
        serverAddress.sin_port = htons(port);

        // 绑定地址和端口
        int ret = bind(listenFd, reinterpret_cast<sockaddr*>(&serverAddress), sizeof(serverAddress));
        if (ret < 0) {
            cerr << "bind failed" << endl;
            return false;
        }

        // 开始监听
        ret = listen(listenFd, USER_LIMIT);
        if (ret < 0) {
            cerr << "listen failed" << endl;
            return false;
        }

        cout << "Server started, listening on " << ip << ":" << port << endl;
        return true;
    }

    // 创建共享内存
    bool createSharedMemory() {
        // 创建共享内存对象
        shmFd = shm_open(shmName.c_str(), O_CREAT | O_RDWR, 0666);
        if (shmFd < 0) {
            cerr << "shm_open failed" << endl;
            return false;
        }

        // 设置共享内存大小
        int ret = ftruncate(shmFd, USER_LIMIT * BUFFER_SIZE);
        if (ret < 0) {
            cerr << "ftruncate failed" << endl;
            return false;
        }

        // 映射共享内存
        shareMem = static_cast<char*>(mmap(nullptr, USER_LIMIT * BUFFER_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shmFd, 0));
        if (shareMem == MAP_FAILED) {
            cerr << "mmap failed" << endl;
            return false;
        }

        // 关闭文件描述符，映射已经建立
        close(shmFd);
        shmFd = -1;
        
        return true;
    }

    // 设置信号处理
    bool setupSignalHandling() {
        // 创建信号管道
        int ret = socketpair(AF_INET, SOCK_STREAM, 0, sigPipeFd);
        if (ret < 0) {
            cerr << "socketpair failed" << endl;
            return false;
        }
        
        setNonBlocking(sigPipeFd[1]);

        // 设置信号处理
        setupSignalHandler(SIGCHLD, [this](int sig) { this->sigHandler(sig); });
        setupSignalHandler(SIGTERM, [this](int sig) { this->sigHandler(sig); });
        setupSignalHandler(SIGINT, [this](int sig) { this->sigHandler(sig); });
        
        // 忽略SIGPIPE信号，防止写关闭的套接字导致进程退出
        signal(SIGPIPE, SIG_IGN);
        
        return true;
    }

    // 启动服务器
    bool start(const char* ip, int port) {
        // 初始化服务器
        if (!init(ip, port)) {
            return false;
        }
        
        // 创建epoll实例
        epollFd = epoll_create(5);
        if (epollFd < 0) {
            cerr << "epoll_create failed" << endl;
            return false;
        }
        
        // 添加监听套接字到epoll
        addFd(epollFd, listenFd);
        
        // 设置信号处理
        if (!setupSignalHandling()) {
            return false;
        }
        
        // 添加信号管道到epoll
        addFd(epollFd, sigPipeFd[0]);
        
        // 创建共享内存
        if (!createSharedMemory()) {
            return false;
        }

        // 主事件循环
        epoll_event events[MAX_EVENT_NUMBER];
        while (!stopServer) {
            int number = epoll_wait(epollFd, events, MAX_EVENT_NUMBER, -1);
            if (number < 0 && errno != EINTR) {
                cerr << "epoll failure" << endl;
                break;
            }

            for (int i = 0; i < number; ++i) {
                int sockFd = events[i].data.fd;
                
                // 新客户端连接
                if (sockFd == listenFd) {
                    handleNewConnection();
                }
                // 信号处理
                else if (sockFd == sigPipeFd[0] && (events[i].events & EPOLLIN)) {
                    handleSignal();
                }
                // 子进程消息
                else if (events[i].events & EPOLLIN) {
                    handleChildMessage(sockFd);
                }
            }
        }
        
        return true;
    }

    // 处理新连接
    void handleNewConnection() {
        sockaddr_in clientAddress;
        socklen_t clientAddrLen = sizeof(clientAddress);
        int connFd = accept(listenFd, reinterpret_cast<sockaddr*>(&clientAddress), &clientAddrLen);
        
        if (connFd < 0) {
            cerr << "accept error: " << strerror(errno) << endl;
            return;
        }
        
        // 检查用户数量是否超过限制
        if (userCount >= USER_LIMIT) {
            const char* info = "too many users\n";
            cout << info;
            send(connFd, info, strlen(info), 0);
            close(connFd);
            return;
        }
        
        // 存储客户端信息
        users[userCount].address = clientAddress;
        users[userCount].connFd = connFd;
        
        // 创建父子进程通信管道
        int ret = socketpair(AF_INET, SOCK_STREAM, 0, users[userCount].pipeFd);
        if (ret < 0) {
            cerr << "socketpair failed" << endl;
            close(connFd);
            return;
        }
        
        // 创建子进程
        pid_t pid = fork();
        if (pid < 0) {
            cerr << "fork failed" << endl;
            close(connFd);
            return;
        }
        else if (pid == 0) {
            // 子进程 关闭不要的文件描述符
            close(epollFd);
            close(listenFd);
            close(users[userCount].pipeFd[0]);
            close(sigPipeFd[0]);
            close(sigPipeFd[1]);
            
            // 运行子进程逻辑
            int result = runChild(userCount, users, shareMem);
            
            // 清理共享内存
            munmap(shareMem, USER_LIMIT * BUFFER_SIZE);
            
            exit(result);
        }
        else {
            // 父进程
            close(connFd);
            close(users[userCount].pipeFd[1]);
            
            // 将管道添加到epoll监听
            addFd(epollFd, users[userCount].pipeFd[0]);
            
            // 记录子进程ID和用户索引的映射
            users[userCount].pid = pid;
            subProcess[pid] = userCount;
            
            // 增加用户计数
            userCount++;
            
            cout << "New client connected. Total clients: " << userCount << endl;
        }
    }

    // 处理信号
    void handleSignal() {
        int sig;
        char signals[1024];
        int ret = recv(sigPipeFd[0], signals, sizeof(signals), 0);
        
        if (ret <= 0) {
            return;
        }
        
        for (int i = 0; i < ret; ++i) {
            switch (signals[i]) {
                case SIGCHLD: {
                    // 子进程退出处理
                    pid_t pid;
                    int stat;
                    while ((pid = waitpid(-1, &stat, WNOHANG)) > 0) {
                        int delUser = subProcess[pid];
                        if (delUser < 0 || delUser > USER_LIMIT) {
                            continue;
                        }
                        
                        cout << "Child process " << pid << " exited, client disconnected" << endl;
                        
                        // 从epoll中删除对应的管道
                        epoll_ctl(epollFd, EPOLL_CTL_DEL, users[delUser].pipeFd[0], nullptr);
                        close(users[delUser].pipeFd[0]);
                        
                        // 如果删除的不是最后一个用户，则将最后一个用户移到当前位置
                        if (delUser != userCount - 1) {
                            users[delUser] = users[userCount - 1];
                            subProcess[users[delUser].pid] = delUser;
                        }
                        
                        // 减少用户计数
                        userCount--;
                    }
                    
                    // 如果已设置终止标志且没有用户了，则停止服务器
                    if (terminate && userCount == 0) {
                        stopServer = true;
                    }
                    break;
                }
                case SIGTERM:
                case SIGINT: {
                    // 终止信号处理
                    cout << "Shutting down server..." << endl;
                    
                    if (userCount == 0) {
                        stopServer = true;
                        break;
                    }
                    
                    // 向所有子进程发送终止信号
                    for (int i = 0; i < userCount; ++i) {
                        int pid = users[i].pid;
                        kill(pid, SIGTERM);
                    }
                    
                    terminate = true;
                    break;
                }
                default:
                    break;
            }
        }
    }

    // 处理子进程消息
    void handleChildMessage(int sockFd) {
        int child = 0;
        int ret = recv(sockFd, reinterpret_cast<char*>(&child), sizeof(child), 0);
        
        if (ret <= 0) {
            return;
        }
        
        // 将消息广播给所有其他客户端
        for (int j = 0; j < userCount; ++j) {
            if (users[j].pipeFd[0] != sockFd) {
                send(users[j].pipeFd[0], reinterpret_cast<char*>(&child), sizeof(child), 0);
            }
        }
    }
};

int main(int argc, char* argv[]) {
    if (argc <= 2) {
        cerr << "Usage: " << argv[0] << " <IP> <Port>" << endl;
        return 1;
    }
    
    const char* ip = argv[1];
    int port = atoi(argv[2]);
    
    // 创建并启动服务器
    ProcessPoolServer server;
    if (server.start(ip, port)) {
        cout << "Server stopped normally" << endl;
        return 0;
    } else {
        cerr << "Server failed to start" << endl;
        return 1;
    }
}